package com.shop.dao.impl;

import com.shop.bean.Goods;
import com.shop.dao.BaseDao;
import com.shop.dao.GoodsDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:zyn
 * @Date:2025/9/19--13:31:51
 */
public class GoodsDaoImpl implements GoodsDao {
    @Override
    public List<Goods> selectGoods(int pageNum, int pageSize) {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet res=null;
        List<Goods> goodsList=new ArrayList<>();
        String sql="SELECT * FROM goods LIMIT ?,?";
        try {
            con= BaseDao.getCon();
            ps=con.prepareStatement(sql);
            ps.setInt(1,(pageNum-1)*pageSize);
            ps.setInt(2,pageSize);
            res=ps.executeQuery();
            while (res.next()){
                Goods goods=new Goods();
                goods.setGoodsId(res.getInt("goodsId"));
                goods.setGoodsName(res.getString("goodsName"));
                goods.setGoodsFactory(res.getString("goodsFactory"));
                goods.setGoodsType(res.getNString("goodsType"));
                goods.setGoodsPrice(res.getDouble("goodsPrice"));
                goods.setGoodsNum(res.getInt("goodsNum"));
                goodsList.add(goods);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeAll(res,ps,con);
        }
        return goodsList;
    }

    @Override
    public int selectGoodsNum() {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet res=null;
        int result=0;
        String sql="SELECT count(1) AS goods_rows FROM goods";
        try {
            con=BaseDao.getCon();
            ps=con.prepareStatement(sql);
            res = ps.executeQuery();
            if(res.next()) {
                result = res.getInt("goods_rows");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeAll(res,ps,con);
        }
        return result;
    }

    @Override
    public int deleteGoodsById(int goodsId) {
        int rows = 0;
        Connection con = null;
        PreparedStatement ps = null;
        String sql = "DELETE FROM goods WHERE goodsId = ?";
        try {
            con = BaseDao.getCon();
            ps = con.prepareStatement(sql);
            ps.setInt(1, goodsId);
            rows = ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(null, ps, con);
        }
        return rows;

    }
}
